package com.management.system.controller;

import com.management.system.beans.user.Params;
import com.management.system.beans.user.TokenParam;
import com.management.system.beans.user.User;
import com.management.system.beans.UserConsumer;
import com.management.system.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@CrossOrigin(origins = "*",maxAge = 3600)
public class UserController {
    @Autowired
    UserServer userServer;

    @GetMapping("/")
    public String out() {
        return "";
    }

    // 查询所有用户
    @GetMapping("/all")
    public UserConsumer all() {
        List<User> list = userServer.all();
        UserConsumer userConsumer = new UserConsumer();
        userConsumer.setCode(200);
        userConsumer.setMessage("操作成功");
        userConsumer.setData(list);
        return userConsumer;
    }

    // 登录接口
    @PostMapping("/login")
    public UserConsumer login(@RequestBody Params params) {
        User user = userServer.login(params.getName());
        UserConsumer userConsumer = new UserConsumer();
        if (user == null) {
            userConsumer.setCode(200);
            userConsumer.setMessage("用户不存在");
            userConsumer.setData(user);
        } else if (!params.getPassword().equals(user.getPassword())) {
            userConsumer.setCode(200);
            userConsumer.setMessage("密码错误");
            userConsumer.setData(null);
        } else {
            userConsumer.setCode(200);
            userConsumer.setMessage("登录成功");
            userConsumer.setData(user);
        }
        return userConsumer;
    }

    // 验证token接口
    @GetMapping("/info")
    public UserConsumer token(@RequestParam("token") String token) {
        TokenParam tokenParam = userServer.token(token);
        tokenParam.setRoles(Collections.singletonList("admin"));
        UserConsumer userConsumer =  new UserConsumer();
        userConsumer.setCode(200);
        userConsumer.setMessage("操作成功");
        userConsumer.setData(tokenParam);
        return userConsumer;
    }

    // 登出接口
    @PostMapping("/logout")
    public UserConsumer logout() {
        UserConsumer userConsumer = new UserConsumer();
        userConsumer.setCode(200);
        userConsumer.setMessage("退出成功");
        userConsumer.setData(null);
        return userConsumer;
    }
}
